//
// Created by 罗宋汤 on 15/8/29.
// Copyright (c) 2015 CHANJET. All rights reserved.
//

#import "CSPJSONResponseSerializer.h"
#import "CSPLogging.h"


@implementation CSPJSONResponseSerializer

- (instancetype)initWithOutputClass:(Class)outputClass {
    self = [super init];
    if (self) {
        _outputClass = outputClass;
    }

    return self;
}

- (BOOL)validateResponse:(NSHTTPURLResponse *)response fromRequest:(NSURLRequest *)request data:(id)data error:(NSError *__autoreleasing *)error {
    return YES;
}

- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
                originalRequest:(NSURLRequest *)originalRequest
                 currentRequest:(NSURLRequest *)currentRequest data:(id)data error:(NSError *__autoreleasing *)error {
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        CSPLogDebug(@"Response header: [%@]", response.allHeaderFields);
    }

    if ([data isKindOfClass:[NSData class]]) {
        CSPLogVerbose(@"Response body: [%@]", [[NSString alloc] initWithData:data
                                                                    encoding:NSUTF8StringEncoding]);
    }

    NSString *responseContentTypeStr = [response allHeaderFields][@"Content-Type"];

    if (responseContentTypeStr) {
        if ([responseContentTypeStr rangeOfString:@"text/html"].location != NSNotFound) {
            //found html response rather than json format. should be an error.
            if (error) {
                NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                *error = [NSError errorWithDomain:CSPGeneralErrorDomain
                                             code:CSPGeneralErrorUnknown
                                         userInfo:@{NSLocalizedDescriptionKey : message? message: [NSNull null]}];
                return nil;
            }
        }
    }

    if (![self validateResponse:response
                    fromRequest:currentRequest
                           data:data
                          error:error]) {
        return nil;
    }


    NSMutableDictionary *resultDic = [NSMutableDictionary new];

    if (response.statusCode >= 200 && response.statusCode < 300 ) {
        // status is good, we can keep NSURL as data
    } else {
        //if status error indicates error, need to convert NSURL to NSData for error processing
        if ([data isKindOfClass:[NSURL class]]) {
            data = [NSData dataWithContentsOfFile:[(NSURL *)data path]];
        }
    }

    id resultObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

//    //TODO: parse response header
//
//    //Parse CSPGeneralError
//    NSDictionary *errorInfo = resultDic[@"error"];
//    if (errorInfo) {
////        if (errorInfo[@"Code"] && errorCodeDictionary[errorInfo[@"Code"]]) {
////            if (error && (*error == nil)) {
////                *error = [NSError errorWithDomain:CSPGeneralErrorDomain
////                                             code:[errorCodeDictionary[errorInfo[@"Code"]] integerValue]
////                                         userInfo:errorInfo
////                ];
////            }
////        }
//    }

    return resultObj;
}


@end